<template>
    <div class="chat-page">
        <!-- 导航栏 -->
        <van-nav-bar title="客服" left-arrow @click-left="onClickLeft" />

        <!-- 消息列表 -->
        <div class="chat-list">
            <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
                <div v-for="(item, index) in list" :key="index" class="chat-item" :class="{ 'self': item.self }">
                    <span class="chat-bubble">{{ item.msg }}</span>
                </div>
            </van-list>
        </div>

        <!-- 底部输入框 -->
        <div class="chat-input">
            <van-field v-model="value" type="textarea" placeholder="请输入您的问题">
                <template #button>
                    <van-button size="small" type="primary" @click="sendMessage">发送</van-button>
                </template>
            </van-field>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from "vue";

const list = ref([]);
const value = ref("");
const loading = ref(false);
const finished = ref(false);

const onClickLeft = () => history.back();

onMounted(() => {
    onLoad();
});

// 组装请求信息
let data = {
    key: "free",
    appid: 0,
    msg: "",
    prefix: "/chat",
};
const sendMessage = async () => {
    // 显示发送消息
    if (value.value.trim()) {
        list.value.push({
            msg: value.value,
            self: true,
        });
        data.msg = value.value;
        value.value = "";
    }
    // 发送请求
    let result = await Api.sendMsg(data);
    // 接收请求结果并显示
    if (result.result == 0) {
        list.value.push({
            msg: result.content,
            self: false
        })
    }
};

const onLoad = () => {
    loading.value = true;
    finished.value = true;
    // setTimeout(() => {
    //     loading.value = false;
    //     if (list.value.length >= 40) finished.value = true;
    // }, 1000);

};

</script>

<style scoped>
/* 让聊天页面占满整个视口 */
.chat-page {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background: #f5f5f5;
}

/* 聊天内容区域 */
.chat-list {
    flex: 1;
    overflow-y: auto;
    padding-bottom: 100px;
    display: flex;
    flex-direction: column;
}

/* 单条消息容器 */
.chat-item {
    display: flex;
    margin: 5px 0;
}

/* 默认（左侧）消息 */
.chat-item .chat-bubble {
    background: white;
    color: black;
    padding: 8px 12px;
    border-radius: 10px;
    display: inline-block;
    max-width: 70%;
    word-break: break-word;
}

/* 自己发的（右侧）消息 */
.chat-item.self {
    justify-content: flex-end;
}

.chat-item.self .chat-bubble {
    background: #4caf50;
    color: white;
}

/* 底部输入框 */
.chat-input {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    display: flex;
    align-items: center;
    background: #fff;
    padding: 10px;
    border-top: 1px solid #ddd;
}

.chat-input .van-field {
    /* flex: 1; */
    margin-right: 10px;
}
</style>
